var ProductId = $('body').data('product-id');

function topSlider () {
    var slider = Swipe(document.getElementById('slider'), {
         auto: 3000,
        continuous: true,
        callback: function(pos) {

          var i = bullets.length;
          
          if( i == 2 ){
            if(pos == 1||pos == 3){
                bullets[0].className = ' ';
                bullets[1].className = 'on';
            }else{
                bullets[1].className = ' ';
                bullets[0].className = 'on';
            }
          }else{
            while (i--) {
                bullets[i].className = ' ';
            }
            bullets[pos].className = 'on';
          }
        }
      });
    if(document.getElementById('slider-position')){
        var bullets = document.getElementById('slider-position').getElementsByTagName('li');
    }
    
}

function navTab () {
    $('#explain-nav').on('click', 'a', function() {
        var _goto = $(this).attr('data-goto');
        $(this).addClass('on').siblings().removeClass('on');
        $('#'+_goto).show().siblings('section').hide();
    });
}

function appDownloadBanner () {
    $(".m-app-download a").on("click", function(e) {
        e.preventDefault();
        var _url, _applink, _type;
        var redirect = false;
        var ua = navigator.userAgent.toLowerCase();
        var iOS = ( ua.match(/(ipad|iphone|ipod)/g) ? true : false );
        var _tripid = $(this).data("trip-id");
        var _userid = $(this).data("user-id");

        if (iOS) { _type = 'ios'; } else{ _type = 'android'; }
        if ( _tripid ) {
            _applink = '/download/?type='+ _type +'&src=mobile&trip_id=' + _tripid;
            _url = 'breadtrip://browsetrip?tripid=' + _tripid;
        }else if( _userid ){
            _applink = '/download/?type='+ _type +'&src=mobile&user_id=' + _userid;
            _url = 'breadtrip://userinfo?userid=' + _userid;
        }else{
            _applink = '/download/?type='+ _type +'&src=mobile';
            _url = iOS ?  'breadtrip://' : 'breadtrip://main';
        }

        // 尝试跳转 App
        window.location = _url;
        // 跳转下载
        window.setTimeout(function() {
            redirect = true;
            window.location = _applink;
        }, 250);
        // window.setTimeout(function() {
        //     if (redirect) {
        //         window.location.reload();
        //     }
        // }, 500);
    });
}


function lazyloadProductInfo () {
    var _section = ['instructions', 'sub', 'schedule', 'flights', 'product-details'];
    $.each(_section, function(i, val) {
        var _temp = $('#temp-' + val);
        if ( _temp.length ) {
            _temp.before(_temp.html());
        }
    });
}
var TIME;
function refreshExpriedCounting(){
    window.clearTimeout(TIME);
    var p = $("#expiredCounting"),
        time = $('#product-countdown').attr('data-time');
        expired = new Date(parseInt(time, 10) * 1000),
        now = new Date(), delta = (expired - now) / 1000,
        minute = parseInt(delta / 60, 10) % 60,
        second = parseInt(delta % 60, 10) + "",
        hour = parseInt(delta / 3600, 10) % 24,
        day = parseInt(delta / (3600 * 24), 10),
        text = "";

    if(!p){
        return;
    }

    if(expired < now) {
        if ( $("#product-countdown").data('seckill') ) {
            $("#product-countdown").remove();
            $('#order-now').removeClass('btn-disable').text('立即预订');
        }else{
            p.text("已过期");
        }
        return;
    }

    if(day > 30){
        p.text("大于30天");
        p.parent().parent().hide();
        return;
    }

    if(day){
        text += day + "天" + hour + "小时" + minute + "分钟" + second + "秒";
    } else if(hour){
        text += hour + "小时" + minute + "分钟" + second + "秒";
    } else if(minute){
        text += minute + "分钟" + second + "秒";
    } else if(second){
        text += second + "秒";
    }
    p.css("font-size", 14);
    p.text(text);
    TIME = setTimeout(function(){
        refreshExpriedCounting();
    }, 250);
}


function seckillEvents (e) {
    $('#order-now').on('click', function (e) {
        e.preventDefault();
        var url = 'http://miaosha.api.breadtrip.com/product/'+ ProductId +'/scramble/';
        $.ajax({
            url: url,
            type: 'POST',
            crossDomain: true,
            dataType: 'json',
            success: function (data) {
                if ( data.error_code === 10001 ) {
                    alert(data.prompt);
                }else if ( data.error_code === 10000 ){
                    alert(data.prompt);
                }else{
                    if ( $('#order-now').data('qualified') !== 1 ) {
                        alert('抢购成功！名额保留30分钟，请马上确认预定，否则视为自动放弃');
                    }
                    window.location.href = data.url;
                }
            },
            xhrFields: {
                withCredentials: true
            }
        });
    });
}

$(document).ready(function() {
    btAppSchema.hideWebViewLoading();
    if ( $('header').attr('data-type') === 'photo' ) {
        topSlider();
    }

    if ( $('#explain-nav').length > 0 ) {
        navTab();
    }

    if ( $('#product-countdown').length > 0 ) {
        if ( $('#product-countdown').data('seckill') ) {
            seckillEvents();
            var url = 'http://miaosha.api.breadtrip.com/product/'+ ProductId +'/?t='+new Date().getTime();
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'jsonp',
                success: function (data) {
                    $('#seckill-stock').html(data.stock);
                    var start_time = data.ts_start_time;
                    var server_time = data.ts_server_time;
                    var local_time = (new Date().getTime())/1000;
                    var delta_start_time = start_time - (server_time - local_time);
                    $('#product-countdown').attr('data-time', delta_start_time);
                    refreshExpriedCounting();
                    if ( data.stock === 0 ) {
                        $('#order-now').text('抢购结束').addClass('btn-disable');
                    }
                    if ( data.qualified ) {
                        $('#order-now').text('立即预订').removeClass('btn-disable').data('qualified', 1);
                    }
                }
            });
        }else{
            refreshExpriedCounting();

        }
    }
    // 大于一个子产品时，下单弹出选择产品框 
    var popupSubproduct = $('#popup-subproduct');
    if(popupSubproduct.length > 0){
        function offMove(e){
            if(e.target == productScroll.get(0) || $.contains(productScroll.get(0),e.target)){
                return;
            }else{
                e.preventDefault();
            }
        }
        $('#popup-subproduct-close').click(function(){
            popupSubproduct.hide();
            $('body').off('touchmove',offMove);

        });
        var productScroll = $('#sub-products-scroll');
        $('#order-now').click(function(e){
            e.preventDefault();
            popupSubproduct.show();
            var popupinner = popupSubproduct.find('.popup-inner');
            popupinner.css('top',($(window).height()-popupinner.height()-64)/2);
            if ( navigator.userAgent.indexOf("Android ") > 0 ) {
                myScroll && myScroll.refresh();
            }
            $('body').on('touchmove',offMove);
        });
        
        if ( productScroll.length >0 && navigator.userAgent.indexOf("Android ") > 0 ) {
            productScroll.removeClass('scrollable');
            var myScroll = new iScroll('sub-products-scroll', {
                hScroll : false
            });
        }
    }
    $('#product-info').on('click', '.detail-title', function() {
        var e = $(this).parent(), showPanel = false;
        e.hasClass("detail-hide") ? showPanel = true : "";
        $(".toggle-detail:not(.detail-hide)").addClass("detail-hide");
        if(showPanel){
            e.removeClass("detail-hide");
            document.body.scrollTop = e.offset().top;
        } else {
            e.addClass("detail-hide");
        }
    });
    appDownloadBanner();
    lazyloadProductInfo();
});
